package com.qingmi.farmer.ui.login;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.qingmi.farmer.R;
import com.qingmi.farmer.data.ActionsCode;
import com.qingmi.farmer.data.UserData;
import com.qingmi.farmer.data.model.UserInfo;
import com.wjjun.base.data.preference.UserPreference;
import com.qingmi.farmer.data.repository.data.BasicDataRepository;
import com.qingmi.farmer.data.repository.data.UserDataRepository;
import com.qingmi.farmer.data.request.GetCodeReq;
import com.qingmi.farmer.data.request.LoginByCodeReq;
import com.qingmi.farmer.data.request.LoginReq;
import com.qingmi.farmer.databinding.ActivityLoginBinding;
import com.wjjun.base.ui.base.BaseActivity;
import com.qingmi.farmer.ui.main.MainActivity;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.wjjun.basemvpvm.data.exception.MyException;
import com.wjjun.basemvpvm.data.model.SimpleEntity;
import com.wjjun.basemvpvm.data.observer.DefaultObserver;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * author Wjjun
 * Created 2018/3/6.
 */

@SuppressWarnings("ConstantConditions")
public class LoginActivity extends BaseActivity<LoginViewModel, ActivityLoginBinding> {

    private final static int EXIT_APP_TIME = 2000;

    public static void startNoToast(Context context) {
        start(context, true);
    }

    public static void start(Context context) {
        ToastUtils.showLong(R.string.error_not_login);
        start(context, true);
    }

    public static void start(Context context, boolean canBack) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(ActionsCode.DATA_CAN_BACK, canBack);
        context.startActivity(intent);
    }


    private static final int COUNT_DOWN_TIME = 120;

    private Disposable disposable;

    @Inject
    BasicDataRepository basicDataRepository;

    @Inject
    UserData userData;

    @Inject
    public UserDataRepository userDataRepository;

    @Inject
    UserPreference userPreference;

    private boolean canBack;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected LoginViewModel initViewModel() {
        return new LoginViewModel();
    }

    @Override
    protected void initContent() {
        userDataRepository.bind(this);
        super.initContent();
        canBack = getIntent().getBooleanExtra(ActionsCode.DATA_CAN_BACK, false);
        userDataRepository.bind(this);

        viewModel.setLeftTimeText(0, getString(R.string.txt_get_code));
        viewModel.isCanBack.set(canBack);
        viewModel.isPwd.set(true);
    }

    @Override
    protected void initData() {
        super.initData();
        String account = userPreference.getAccount();
        if (!TextUtils.isEmpty(account)) {
            viewModel.account.set(account);
            viewDataBinding.editPwd.requestFocus();
        }
    }


    @SuppressWarnings("ConstantConditions")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_register:  //注册
                break;
            case R.id.tv_forgot_pwd:// 找回密码
                break;
            case R.id.tv_get_code:  //获取验证码
                getCode();
                break;
            case R.id.tv_change_login:  //转换登录模式
                viewModel.isPwd.set(!viewModel.isPwd.get());
                break;
            case R.id.btn_login://登录
                loginUmeng();
                break;
            case R.id.iv_back:  //返回
                finish();
                break;
        }
    }

    private void getCode() {
        String phone = viewModel.account.get();
        if (TextUtils.isEmpty(phone)) {
            showToast(R.string.error_phone_is_empty);
            return;
        }
        if (phone.length() != 11) {
            showToast(R.string.error_phone_is_error);
            return;
        }

        showLoadingDialog("");
        GetCodeReq req = GetCodeReq.getLoginCode(phone);
        basicDataRepository.getCode(new DefaultObserver<SimpleEntity>() {
            @Override
            public void onNext(SimpleEntity simpleEntity) {
                startTime();
                dismissLoadingDialog();
            }

            @Override
            public void onError(MyException e) {
                dismissLoadingDialog();
                showToast(e.getMessage());
            }
        }, req);
    }

    /**
     * 启动定时器
     */
    public void startTime() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(COUNT_DOWN_TIME + 1)//设置总共发送的次数
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return COUNT_DOWN_TIME - aLong;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (disposable != null) {
                            disposable.dispose();
                        }
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        viewModel.setLeftTimeText(aLong.intValue(), getString(R.string.txt_get_code_time, aLong));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        viewModel.setLeftTimeText(0, getString(R.string.txt_get_code));
                        closeTimer();
                    }
                });
    }


    /**
     * 关闭定时器
     */
    public void closeTimer() {
        if (disposable != null) {
            disposable.dispose();
        }
    }

    /**
     * 登录umeng推送
     */
    private void loginUmeng() {
        if (!TextUtils.isEmpty(userPreference.getUmengToken())) {
            login();
            return;
        }
        showLoadingDialog("");
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                Log.e("Umeng Token:", deviceToken);
                userPreference.setUmengToken(deviceToken);
                login();
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("Umeng register:", s + s1);
                login();

            }
        });
    }

    private void login() {
        if (viewModel.isPwd.get()) {    //使用账户密码
            toLogin();
        } else {    //使用验证码
            loginByCode();
        }
    }

    /**
     * 验证码登录
     */
    private void loginByCode() {
        String phone = viewModel.account.get();
        if (TextUtils.isEmpty(phone)) {
            showToast(R.string.error_phone_is_empty);
            return;
        }
        if (phone.length() != 11) {
            showToast(R.string.error_phone_is_error);
            return;
        }
        String code = viewModel.code.get();
        if (TextUtils.isEmpty(code)) {
            showToast(R.string.error_code_is_empty);
            return;
        }
        if (code.length() != 6) {
            showToast(R.string.error_code_is_error);
            return;
        }

        showLoadingDialog(R.string.loading_login);
        userDataRepository.loginByCode(new DefaultObserver<UserInfo>() {
            @Override
            public void onNext(UserInfo userInfo) {
                loginSuccess(userInfo);
            }

            @Override
            public void onError(MyException e) {
                dismissLoadingDialog();
                showToast(e.getMessage());
            }
        }, new LoginByCodeReq(phone, code));
    }

    //监听密码框的options事件
    public final TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            loginUmeng();
            return true;
        }
    };

    /**
     * 账户密码登录
     */
    private void toLogin() {
        if (TextUtils.isEmpty(viewModel.account.get())) {
            showToast(R.string.error_account_is_empty);
            return;
        }
        if (TextUtils.isEmpty(viewModel.psw.get())) {
            showToast(R.string.error_pwd_is_empty);
            return;
        }

        userPreference.setAccount(viewModel.account.get());

        showLoadingDialog(R.string.loading_login);
        LoginReq param = new LoginReq(viewModel.account.get(), EncryptUtils.encryptMD5ToString(viewModel.psw.get()));
        userDataRepository.login(new DefaultObserver<UserInfo>() {

            @Override
            public void onNext(UserInfo userInfo) {
                loginSuccess(userInfo);
            }

            @Override
            public void onError(MyException e) {
                dismissLoadingDialog();
                showToast(e.getMessage());
            }
        }, param);
    }

    private void loginSuccess(UserInfo userInfo) {
        dismissLoadingDialog();

            ActivityUtils.finishOtherActivities(LoginActivity.class);
            MainActivity.start(this);


        finish();
    }

    @Override
    public void onToolBarLeftClick() {
        if (canBack) {
            finish();
        } else {
            ActivityUtils.finishAllActivities();
            System.exit(0);
        }
    }

    private long mExitTime;

    @Override
    public void onBackPressed() {
        if (canBack) {
            super.onBackPressed();
            return;
        }
        if ((System.currentTimeMillis() - mExitTime) > EXIT_APP_TIME) {
            Toast.makeText(this, R.string.txt_exit_app, Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            onToolBarLeftClick();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeTimer();
    }
}
